<!DOCTYPE html>


<html lang="zh-CN">


<head>
  <meta charset="utf-8" />
    
  <meta name="description" content="welcome" />
  
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
  <title>
    ConcurrentHashMap（JDK8）待补充 |  ChenyyのBlog
  </title>
  <meta name="generator" content="hexo-theme-ayer">
  
  <link rel="shortcut icon" href="/favicon.ico" />
  
  
<link rel="stylesheet" href="/dist/main.css">

  <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/css/remixicon.min.css">
  
<link rel="stylesheet" href="/css/custom.css">

  
  <script src="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script>
  
  

  

</head>

</html>

<body>
  <div id="app">
    
      
    <main class="content on">
      <section class="outer">
  <article
  id="post-Java/ConcurrentHashMap（JDK8）"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  ConcurrentHashMap（JDK8）待补充
</h1>
 

    </header>
     
    <div class="article-meta">
      <a href="/2021/05/14/Java/ConcurrentHashMap%EF%BC%88JDK8%EF%BC%89/" class="article-date">
  <time datetime="2021-05-14T02:21:58.000Z" itemprop="datePublished">2021-05-14</time>
</a> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/Java/">Java</a>
  </div>
  
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> 字数统计:</span>
            <span class="post-count">2.4k</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> 阅读时长≈</span>
            <span class="post-count">9 分钟</span>
        </span>
    </span>
</div>
 
    </div>
      
    <div class="tocbot"></div>




  
    <div class="article-entry" itemprop="articleBody">
       
  <ul>
<li>回顾以前对象依赖</li>
<li>对比</li>
<li>特性</li>
<li>使用场景</li>
</ul>
<span id="more"></span>

<h1 id="对比"><a href="#对比" class="headerlink" title="对比"></a>对比</h1><h2 id="与HashMap的区别是什么？"><a href="#与HashMap的区别是什么？" class="headerlink" title="与HashMap的区别是什么？"></a>与HashMap的区别是什么？</h2><p>ConcurrentHashMap是HashMap的升级版，HashMap是线程不安全的，而ConcurrentHashMap是线程安全。而其他功能和实现原理和HashMap类似。</p>
<h2 id="与Hashtable的区别是什么？"><a href="#与Hashtable的区别是什么？" class="headerlink" title="与Hashtable的区别是什么？"></a>与Hashtable的区别是什么？</h2><p>Hashtable也是线程安全的，但每次要锁住整个结构，并发性低。相比之下，ConcurrentHashMap获取size时才锁整个对象。</p>
<p>Hashtable对get/put/remove都使用了同步操作。ConcurrentHashMap只对put/remove同步。</p>
<p>Hashtable是快速失败的，遍历时改变结构会报错ConcurrentModificationException。ConcurrentHashMap是安全失败，允许并发检索和更新。</p>
<h2 id="JDK8的ConcurrentHashMap和JDK7的ConcurrentHashMap有什么区别？"><a href="#JDK8的ConcurrentHashMap和JDK7的ConcurrentHashMap有什么区别？" class="headerlink" title="JDK8的ConcurrentHashMap和JDK7的ConcurrentHashMap有什么区别？"></a>JDK8的ConcurrentHashMap和JDK7的ConcurrentHashMap有什么区别？</h2><ol>
<li>JDK8中新增了红黑树</li>
<li>JDK7中使用的是头插法，JDK8中使用的是尾插法</li>
<li>JDK7中使用了分段锁，而JDK8中没有使用分段锁了</li>
<li>JDK7中使用了ReentrantLock，JDK8中没有使用ReentrantLock了，而使用了Synchronized</li>
<li>JDK7中的扩容是每个Segment内部进行扩容，不会影响其他Segment，而JDK8中的扩容和HashMap的扩容类似，只不过支持了多线程扩容，并且保证了线程安全</li>
</ol>
<h1 id="特性"><a href="#特性" class="headerlink" title="特性"></a>特性</h1><h2 id="ConcurrentHashMap是如何保证并发安全的？"><a href="#ConcurrentHashMap是如何保证并发安全的？" class="headerlink" title="ConcurrentHashMap是如何保证并发安全的？"></a>ConcurrentHashMap是如何保证并发安全的？</h2><p>JDK7中ConcurrentHashMap是通过ReentrantLock+CAS+分段思想来保证的并发安全的，ConcurrentHashMap的put方法会通过CAS的方式，把一个Segment对象存到Segment数组中，一个Segment内部存在一个HashEntry数组，相当于分段的HashMap，Segment继承了ReentrantLock，每段put开始会加锁。</p>
<p>在JDK7的ConcurrentHashMap中，首先有一个Segment数组，存的是Segment对象，Segment相当于一个小HashMap，Segment内部有一个HashEntry的数组，也有扩容的阈值，同时Segment继承了ReentrantLock类，同时在Segment中还提供了put，get等方法，比如Segment的put方法在一开始就会去加锁，加到锁之后才会把key,value存到Segment中去，然后释放锁。同时在ConcurrentHashMap的put方法中，会通过CAS的方式把一个Segment对象存到Segment数组的某个位置中。同时因为一个Segment内部存在一个HashEntry数组，所以和HashMap对比来看，相当于分段了，每段里面是一个小的HashMap，每段公用一把锁，同时在ConcurrentHashMap的构造方法中是可以设置分段的数量的，叫做并发级别concurrencyLevel.</p>
<p>JDK8中ConcurrentHashMap是通过synchronized+cas来实现了。在JDK8中只有一个数组，就是Node数组，Node就是key，value，hashcode封装出来的对象，和HashMap中的Entry一样，在JDK8中通过对Node数组的某个index位置的元素进行同步，达到该index位置的并发安全。同时内部也利用了CAS对数组的某个位置进行并发安全的赋值。</p>
<h2 id="JDK8中的ConcurrentHashMap为什么使用synchronized来进行加锁？"><a href="#JDK8中的ConcurrentHashMap为什么使用synchronized来进行加锁？" class="headerlink" title="JDK8中的ConcurrentHashMap为什么使用synchronized来进行加锁？"></a>JDK8中的ConcurrentHashMap为什么使用synchronized来进行加锁？</h2><p>JDK8中使用synchronized加锁时，是对链表头结点和红黑树根结点来加锁的，而ConcurrentHashMap会保证，数组中某个位置的元素一定是链表的头结点或红黑树的根结点，所以JDK8中的ConcurrentHashMap在对某个桶进行并发安全控制时，只需要使用synchronized对当前那个位置的数组上的元素进行加锁即可，对于每个桶，只有获取到了第一个元素上的锁，才能操作这个桶，不管这个桶是一个链表还是红黑树。</p>
<p>想比于JDK7中使用ReentrantLock来加锁，因为JDK7中使用了分段锁，所以对于一个ConcurrentHashMap对象而言，分了几段就得有几个ReentrantLock对象，表示得有对应的几把锁。</p>
<p>而JDK8中使用synchronized关键字来加锁就会更节省内存，并且jdk也已经对synchronized的底层工作机制进行了优化，效率更好。</p>
<h1 id="扩容"><a href="#扩容" class="headerlink" title="扩容"></a>扩容</h1><p><a target="_blank" rel="noopener" href="https://blog.csdn.net/ZOKEKAI/article/details/90051567">https://blog.csdn.net/ZOKEKAI/article/details/90051567</a></p>
<p><a target="_blank" rel="noopener" href="https://www.cnblogs.com/twoheads/p/10712349.html">https://www.cnblogs.com/twoheads/p/10712349.html</a></p>
<h2 id="JDK7中的ConcurrentHashMap是如何扩容的？"><a href="#JDK7中的ConcurrentHashMap是如何扩容的？" class="headerlink" title="JDK7中的ConcurrentHashMap是如何扩容的？"></a>JDK7中的ConcurrentHashMap是如何扩容的？</h2><p>JDK7中的ConcurrentHashMap和JDK7的HashMap的扩容是不太一样的，首先JDK7中也是支持多线程扩容的，原因是，JDK7中的ConcurrentHashMap分段了，每一段叫做Segment对象，每个Segment对象相当于一个HashMap，分段之后，对于ConcurrentHashMap而言，能同时支持多个线程进行操作，前提是这些操作的是不同的Segment，而ConcurrentHashMap中的扩容是仅限于本Segment，也就是对应的小型HashMap进行扩容，所以是可以多线程扩容的。</p>
<p>每个Segment内部的扩容逻辑和HashMap中一样。</p>
<h2 id="JDK8中的ConcurrentHashMap是如何扩容的？"><a href="#JDK8中的ConcurrentHashMap是如何扩容的？" class="headerlink" title="JDK8中的ConcurrentHashMap是如何扩容的？"></a>JDK8中的ConcurrentHashMap是如何扩容的？</h2><p>首先，JDK8中是支持多线程扩容的，JDK8中的ConcurrentHashMap不再是分段，或者可以理解为每个桶为一段，在需要扩容时，首先会生成一个双倍大小的数组，生成完数组后，线程就会开始转移元素，在扩容的过程中，如果有其他线程在put，那么这个put线程会帮助去进行元素的转移，虽然叫转移，但是其实是基于原数组上的Node信息去生成一个新的Node的，也就是原数组上的Node不会消失，因为在扩容的过程中，如果有其他线程在get也是可以的。</p>
<h2 id="JDK8中的ConcurrentHashMap有一个CounterCell，你是如何理解的？"><a href="#JDK8中的ConcurrentHashMap有一个CounterCell，你是如何理解的？" class="headerlink" title="JDK8中的ConcurrentHashMap有一个CounterCell，你是如何理解的？"></a>JDK8中的ConcurrentHashMap有一个CounterCell，你是如何理解的？</h2><p>CounterCell是JDK8中用来统计ConcurrentHashMap中所有元素个数的，在统计ConcurentHashMap时，不能直接对ConcurrentHashMap对象进行加锁然后再去统计，因为这样会影响ConcurrentHashMap的put等操作的效率，在JDK8的实现中使用了CounterCell+baseCount来辅助进行统计，baseCount是ConcurrentHashMap中的一个属性，某个线程在调用ConcurrentHashMap对象的put操作时，会先通过CAS去修改baseCount的值，如果CAS修改成功，就计数成功，如果CAS修改失败，则会从CounterCell数组中随机选出一个CounterCell对象，然后利用CAS去修改CounterCell对象中的值，因为存在CounterCell数组，所以，当某个线程想要计数时，先尝试通过CAS去修改baseCount的值，如果没有修改成功，则从CounterCell数组中随机取出来一个CounterCell对象进行CAS计数，这样在计数时提高了效率。</p>
<p>所以ConcurrentHashMap在统计元素个数时，就是baseCount加上所有CountCeller中的value值，所得的和就是所有的元素个数。</p>
<h1 id="使用场景"><a href="#使用场景" class="headerlink" title="使用场景"></a>使用场景</h1><h3 id="多用户同时登入和登出"><a href="#多用户同时登入和登出" class="headerlink" title="多用户同时登入和登出"></a>多用户同时登入和登出</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">// 在线用户管理类</span><br><span class="line">public class UserManager &#123;</span><br><span class="line">    private Map&lt;String, User&gt; userMap = new ConcurrentHashMap&lt;&gt;();</span><br><span class="line">    </span><br><span class="line">    // 当用户登入时调用</span><br><span class="line">    public void onUserSignIn(String sessionId, User user) &#123;</span><br><span class="line">        this.userMap.put(sessionId, user);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    // 当用户登出或超时时调用</span><br><span class="line">    public void onUserSignOut(String sessionId) &#123;</span><br><span class="line">        this.userMap.remove(sessionId);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    public getUser(String sessionId) &#123;</span><br><span class="line">        return this.userMap.get(sessionId);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>





<h3 id="统计文本单词"><a href="#统计文本单词" class="headerlink" title="统计文本单词"></a>统计文本单词</h3><p>多线程统计文本单词，下面代码会出现BUG</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">ConcurrentHashMap map  = new ConcurrentHashMap&lt;String,Integer&gt;();</span><br><span class="line"></span><br><span class="line">//下面多线程运行，会出现BUG</span><br><span class="line">Integer value= map.get(word);</span><br><span class="line">if (value==null)&#123;</span><br><span class="line">    map.put(word,1);</span><br><span class="line">&#125;else &#123;</span><br><span class="line">    map.put(word,value++);</span><br><span class="line">&#125;computeIfAbsent</span><br></pre></td></tr></table></figure>

<p>ConcurrentHashMap可以保证单个get/put操作的原子性，但是不能保证两个一起就是原子性。</p>
<p>如何解决？ ConcurrentHashMap提供了两个方法</p>
<ul>
<li><code>computeIfAbsent</code>：计算如果不存在。如果key不存在，存入计算结果并返回</li>
<li><code>computeIfPresent</code>：计算如果存在。如果key存在，计算公式并返回</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">ConcurrentHashMap&lt;String,Integer&gt; map  = new ConcurrentHashMap&lt;&gt;();</span><br><span class="line">Integer a1 = map.computeIfAbsent(&quot;a&quot;, (key) -&gt; 1+1);</span><br><span class="line">Integer a2 = map.computeIfPresent(&quot;a&quot;, (key,value) -&gt; map.get(key)+value);</span><br><span class="line">System.out.println(a1);// 2</span><br><span class="line">System.out.println(a2);// 4</span><br></pre></td></tr></table></figure>

<p>将Integer替换为原子类LongAdder，解决多线程a++问题即可。</p>
<h3 id="存储线程资源池，为每种请求类型创建一个线程池"><a href="#存储线程资源池，为每种请求类型创建一个线程池" class="headerlink" title="存储线程资源池，为每种请求类型创建一个线程池"></a>存储线程资源池，为每种请求类型创建一个线程池</h3><p>初始化一个成员变量map。当请求到达时，检查map中是否已经存在创建好的线程池即可，如果存在则返回，如果不存在就创建一个新的线程池放入map中，同时返回新创建的线程池。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">public ThreadPool getThreadPool(String type) &#123;</span><br><span class="line"></span><br><span class="line">    RingBuffer&lt;StringEvent&gt; disruptor = threadPoolMap.get(type);</span><br><span class="line">    if (disruptor == null) &#123;</span><br><span class="line">        synchronized (this) &#123;</span><br><span class="line">            disruptor = threadPoolMap.get(type);</span><br><span class="line">            if (disruptor == null) &#123;</span><br><span class="line">                threadPoolMap.put(type, createThreadPool(type));</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    return threadPoolMap.get(type);</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>使用ConcurrentHashMap的性能会比单纯的使用synchronized+hashMap高很多。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">   public ThreadPool getThreadPool(String type) &#123;</span><br><span class="line"></span><br><span class="line">    RingBuffer&lt;StringEvent&gt; disruptor = threadPoolMap.get(type);</span><br><span class="line">    if (disruptor == null) &#123;</span><br><span class="line">        threadPoolMap.computeIfAbsent(type, (key) -&gt; createThreadPool(type));</span><br><span class="line">       &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    return threadPoolMap.get(type);</span><br></pre></td></tr></table></figure>



<h3 id="读超过写，作为缓存"><a href="#读超过写，作为缓存" class="headerlink" title="读超过写，作为缓存"></a>读超过写，作为缓存</h3><p>CHM适用于做cache，在程序启动时初始化，之后可以被多个请求线程访问。</p>
<ul>
<li><p>当写者数量大于等于读者时，CHM的性能是低于Hashtable和synchronized Map的。</p>
</li>
<li><p>因为当锁住了整个Map时，读操作要等待对同一部分执行写操作的线程结束。</p>
</li>
<li><p>CHM是HashTable一个很好的替代，但CHM的比HashTable的同步性稍弱。</p>
</li>
</ul>
<h3 id="获取操作get与更新操作交迭（包括-put-和-remove）"><a href="#获取操作get与更新操作交迭（包括-put-和-remove）" class="headerlink" title="获取操作get与更新操作交迭（包括 put 和 remove）"></a>获取操作get与更新操作交迭（包括 put 和 remove）</h3><p>遍历过程中，集合结构变化，不会抛出ConcurrentModificationException，能够正常遍历完成。</p>
<p><strong>原因：</strong></p>
<p>1、读写不互斥，其他线程修改容器中部分副本时，读操作不受影响。</p>
<p>2、hapend-before机制，避免读取到更新前的数据。</p>
<p>3、读写机制通过violatile实现，迭代时、数组扩容时保证数据的可见性，不会出现数组越界等异常。</p>
<p><strong>源码解析：</strong></p>
<p><img src="https://gitee.com/chenyy-2017/pic/raw/master/note/20210514192847.png"></p>
<p>参考：</p>
<p>关于jdk1.8中ConcurrentHashMap的方方面面：<a target="_blank" rel="noopener" href="https://blog.csdn.net/tp7309/article/details/76532366">https://blog.csdn.net/tp7309/article/details/76532366</a></p>
<p>ConcurrentHashMap源码分析（JDK1.8）：<a target="_blank" rel="noopener" href="https://blog.csdn.net/ji1162765575/article/details/111309612">https://blog.csdn.net/ji1162765575/article/details/111309612</a></p>
<p>ConcurrentHashMap为何不会出现ConcurrentModificationException异常：<a target="_blank" rel="noopener" href="https://www.bbsmax.com/A/6pdDgqbq5w/">https://www.bbsmax.com/A/6pdDgqbq5w/</a></p>
<p>concurrentHashMap对concurrentModificationException的处理：<a target="_blank" rel="noopener" href="https://www.jianshu.com/p/0b769a8779f6">https://www.jianshu.com/p/0b769a8779f6</a></p>
<p>ConcurrentHashMap源码分析（JDK8） get/put/remove方法分析：<a target="_blank" rel="noopener" href="https://www.jianshu.com/p/5bc70d9e5410">https://www.jianshu.com/p/5bc70d9e5410</a></p>
<p>ConcurrentHashMap的错误使用：<a target="_blank" rel="noopener" href="https://zhuanlan.zhihu.com/p/113379816">https://zhuanlan.zhihu.com/p/113379816</a></p>
<p>什么时候使用ConcurrentHashMap：<a target="_blank" rel="noopener" href="https://my.oschina.net/u/3847203/blog/3084619">https://my.oschina.net/u/3847203/blog/3084619</a></p>
<p>ConcurrentHashMap的使用场景：<a target="_blank" rel="noopener" href="https://blog.csdn.net/a_fengzi_code_110/article/details/61191591">https://blog.csdn.net/a_fengzi_code_110/article/details/61191591</a></p>
 
      <!-- reward -->
      
      <div id="reword-out">
        <div id="reward-btn">
          打赏
        </div>
      </div>
      
    </div>
    

    <!-- copyright -->
    
    <div class="declare">
      <ul class="post-copyright">
        <li>
          <i class="ri-copyright-line"></i>
          <strong>版权声明： </strong>
          
          本博客所有文章除特别声明外，著作权归作者所有。转载请注明出处！
          
        </li>
      </ul>
    </div>
    
    <footer class="article-footer">
       
<div class="share-btn">
      <span class="share-sns share-outer">
        <i class="ri-share-forward-line"></i>
        分享
      </span>
      <div class="share-wrap">
        <i class="arrow"></i>
        <div class="share-icons">
          
          <a class="weibo share-sns" href="javascript:;" data-type="weibo">
            <i class="ri-weibo-fill"></i>
          </a>
          <a class="weixin share-sns wxFab" href="javascript:;" data-type="weixin">
            <i class="ri-wechat-fill"></i>
          </a>
          <a class="qq share-sns" href="javascript:;" data-type="qq">
            <i class="ri-qq-fill"></i>
          </a>
          <a class="douban share-sns" href="javascript:;" data-type="douban">
            <i class="ri-douban-line"></i>
          </a>
          <!-- <a class="qzone share-sns" href="javascript:;" data-type="qzone">
            <i class="icon icon-qzone"></i>
          </a> -->
          
          <a class="facebook share-sns" href="javascript:;" data-type="facebook">
            <i class="ri-facebook-circle-fill"></i>
          </a>
          <a class="twitter share-sns" href="javascript:;" data-type="twitter">
            <i class="ri-twitter-fill"></i>
          </a>
          <a class="google share-sns" href="javascript:;" data-type="google">
            <i class="ri-google-fill"></i>
          </a>
        </div>
      </div>
</div>

<div class="wx-share-modal">
    <a class="modal-close" href="javascript:;"><i class="ri-close-circle-line"></i></a>
    <p>扫一扫，分享到微信</p>
    <div class="wx-qrcode">
      <img src="//api.qrserver.com/v1/create-qr-code/?size=150x150&data=http://example.com/2021/05/14/Java/ConcurrentHashMap%EF%BC%88JDK8%EF%BC%89/" alt="微信分享二维码">
    </div>
</div>

<div id="share-mask"></div>  
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/" rel="tag">数据结构</a></li></ul>

    </footer>
  </div>

   
  <nav class="article-nav">
    
      <a href="/2021/05/15/resource/finance/E%E5%A4%A7%E5%B9%B2%E8%B4%A7%E5%90%88%E9%9B%86/" class="article-nav-link">
        <strong class="article-nav-caption">上一篇</strong>
        <div class="article-nav-title">
          
            E大干货合集
          
        </div>
      </a>
    
    
      <a href="/2021/05/09/resource/finance/E%E5%A4%A7%E7%9A%84%E6%8A%95%E8%B5%84%E7%AC%94%E8%AE%B0/" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">E大的投资笔记：资产配置</div>
      </a>
    
  </nav>

   
<!-- valine评论 -->
<div id="vcomments-box">
  <div id="vcomments"></div>
</div>
<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/valine@1.4.14/dist/Valine.min.js"></script>
<script>
  new Valine({
    el: "#vcomments",
    app_id: "",
    app_key: "",
    path: window.location.pathname,
    avatar: "monsterid",
    placeholder: "给我的文章加点评论吧~",
    recordIP: true,
  });
  const infoEle = document.querySelector("#vcomments .info");
  if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0) {
    infoEle.childNodes.forEach(function (item) {
      item.parentNode.removeChild(item);
    });
  }
</script>
<style>
  #vcomments-box {
    padding: 5px 30px;
  }

  @media screen and (max-width: 800px) {
    #vcomments-box {
      padding: 5px 0px;
    }
  }

  #vcomments-box #vcomments {
    background-color: #fff;
  }

  .v .vlist .vcard .vh {
    padding-right: 20px;
  }

  .v .vlist .vcard {
    padding-left: 10px;
  }
</style>

 
   
     
</article>

</section>
      <footer class="footer">
  <div class="outer">
    <ul>
      <li>
        Copyrights &copy;
        2021
        <i class="ri-heart-fill heart_icon"></i> Chenyy
      </li>
    </ul>
    <ul>
      <li>
        
      </li>
    </ul>
    <ul>
      <li>
        
        
        <span>
  <span><i class="ri-user-3-fill"></i>访问人数:<span id="busuanzi_value_site_uv"></span></s>
  <span class="division">|</span>
  <span><i class="ri-eye-fill"></i>浏览次数:<span id="busuanzi_value_page_pv"></span></span>
</span>
        
      </li>
    </ul>
    <ul>
      
    </ul>
    <ul>
      
    </ul>
    <ul>
      <li>
        <!-- cnzz统计 -->
        
        <script type="text/javascript" src='https://s9.cnzz.com/z_stat.php?id=1278069914&amp;web_id=1278069914'></script>
        
      </li>
    </ul>
  </div>
</footer>
      <div class="float_btns">
        <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>

<div class="todark" id="todark">
  <i class="ri-moon-line"></i>
</div>

      </div>
    </main>
    <aside class="sidebar on">
      <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="/images/ayer-side.svg" alt="ChenyyのBlog"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">文章</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/categories">分类</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags">标签</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/book">收藏</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/about/me">关于我</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      <a class="nav-item-link nav-item-search"  title="搜索">
        <i class="ri-search-line"></i>
      </a>
      
      
      <a class="nav-item-link" target="_blank" href="/atom.xml" title="RSS Feed">
        <i class="ri-rss-line"></i>
      </a>
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
    </aside>
    <script>
      if (window.matchMedia("(max-width: 768px)").matches) {
        document.querySelector('.content').classList.remove('on');
        document.querySelector('.sidebar').classList.remove('on');
      }
    </script>
    <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>请我喝杯咖啡吧~</p>
  <div class="reward-box">
    
    
  </div>
</div>
    
<script src="/js/jquery-2.0.3.min.js"></script>


<script src="/js/lazyload.min.js"></script>

<!-- Tocbot -->


<script src="/js/tocbot.min.js"></script>

<script>
  tocbot.init({
    tocSelector: '.tocbot',
    contentSelector: '.article-entry',
    headingSelector: 'h1, h2, h3, h4, h5, h6',
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer: 'main',
    positionFixedSelector: '.tocbot',
    positionFixedClass: 'is-position-fixed',
    fixedSidebarOffset: 'auto'
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css">
<script src="https://cdn.jsdelivr.net/npm/justifiedGallery@3.7.0/dist/js/jquery.justifiedGallery.min.js"></script>

<script src="/dist/main.js"></script>

<!-- ImageViewer -->

<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.min.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script>

<!-- MathJax -->

<!-- Katex -->

<!-- busuanzi  -->


<script src="/js/busuanzi-2.3.pure.min.js"></script>


<!-- ClickLove -->

<!-- ClickBoom1 -->

<!-- ClickBoom2 -->

<!-- CodeCopy -->


<link rel="stylesheet" href="/css/clipboard.css">

<script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
  function wait(callback, seconds) {
    var timelag = null;
    timelag = window.setTimeout(callback, seconds);
  }
  !function (e, t, a) {
    var initCopyCode = function(){
      var copyHtml = '';
      copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
      copyHtml += '<i class="ri-file-copy-2-line"></i><span>COPY</span>';
      copyHtml += '</button>';
      $(".highlight .code pre").before(copyHtml);
      $(".article pre code").before(copyHtml);
      var clipboard = new ClipboardJS('.btn-copy', {
        target: function(trigger) {
          return trigger.nextElementSibling;
        }
      });
      clipboard.on('success', function(e) {
        let $btn = $(e.trigger);
        $btn.addClass('copied');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-checkbox-circle-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPIED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-checkbox-circle-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
      clipboard.on('error', function(e) {
        e.clearSelection();
        let $btn = $(e.trigger);
        $btn.addClass('copy-failed');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-time-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPY FAILED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-time-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
    }
    initCopyCode();
  }(window, document);
</script>


<!-- CanvasBackground -->


    
  </div>
</body>

</html>